import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableModule, MatTableDataSource } from '@angular/material/table';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { CommonModule } from '@angular/common';
import { CdkVirtualScrollViewport, ScrollingModule } from '@angular/cdk/scrolling';
import { BehaviorSubject, Observable } from 'rxjs';
import { startWith } from 'rxjs/operators';

export interface UserData {
  id: number;
  name: string;
  email: string;
  role: string;
}

@Component({
  selector: 'app-scroll-table',
  templateUrl: './scroll-table.component.html',
  styleUrls: ['./scroll-table.component.css'],
  standalone: true,
  imports: [
    CommonModule,
    MatTableModule,
    MatProgressSpinnerModule,
    ScrollingModule
  ]
})
export class ScrollTableComponent implements OnInit {
  displayedColumns: string[] = ['id', 'name', 'email', 'role'];
  dataSource = new MatTableDataSource<UserData>([]);
  isLoading = false;
  pageSize = 20;
  currentPage = 0;
  totalItems = 100;
  
  private dataSubject = new BehaviorSubject<UserData[]>([]);
  data$: Observable<UserData[]> = this.dataSubject.asObservable().pipe(
    startWith([])
  );

  @ViewChild(CdkVirtualScrollViewport) viewport!: CdkVirtualScrollViewport;

  constructor() {}

  ngOnInit() {
    this.loadData();
  }

  loadData() {
    if (this.isLoading || this.dataSource.data.length >= this.totalItems) {
      return;
    }

    this.isLoading = true;
    setTimeout(() => {
      const newData = this.generateData(this.currentPage * this.pageSize, this.pageSize);
      this.dataSource.data = [...this.dataSource.data, ...newData];
      this.currentPage++;
      this.isLoading = false;
    }, 1000);
  }

  onScroll() {
    const viewport = this.viewport;
    const viewportSize = viewport.getViewportSize();
    const scrollOffset = viewport.measureScrollOffset();
    const contentSize = viewport.getDataLength() * 50; // 50 是 itemSize 的值
    
    if (scrollOffset + viewportSize >= contentSize - 100 && !this.isLoading) {
      this.loadData();
    }
  }

  private generateData(startIndex: number, count: number): UserData[] {
    const roles = ['Admin', 'User', 'Manager', 'Developer', 'Designer', 'Tester'];
    const domains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com'];
    const firstNames = ['张', '王', '李', '赵', '刘', '陈', '杨', '黄', '周', '吴'];
    const lastNames = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '军'];

    return Array.from({ length: count }, (_, i) => {
      const id = startIndex + i + 1;
      const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
      const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
      const domain = domains[Math.floor(Math.random() * domains.length)];
      
      return {
        id: id,
        name: `${firstName}${lastName}`,
        email: `${firstName.toLowerCase()}${lastName.toLowerCase()}${id}@${domain}`,
        role: roles[Math.floor(Math.random() * roles.length)]
      };
    });
  }
} 